/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.creativor.rayson.serialize;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Array;

/**
 * @author creativor
 * 
 */
final class DoubleType extends SerializableType<Double> {

	/**
	 * @param type
	 */
	protected DoubleType(final byte type) {
		super(type);
	}

	@Override
	public Double read(final DataInput dis) throws SerializeFormatException, IOException {
		return dis.readDouble();
	}

	@Override
	Object readArray(final DataInput dis, final int arrayLength) throws SerializeFormatException,
			IOException {
		final Object array = Array.newInstance(Double.TYPE, arrayLength);
		for (int i = 0; i < arrayLength; i++) {
			try {
				Array.setDouble(array, i, read(dis));
			} catch (ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
				// Ignore it.
			}
		}
		return array;
	}

	@Override
	public void write(final DataOutput dos, final Double value) throws IOException {
		dos.writeDouble(value);
	}

	@Override
	void writeArray(final DataOutput dos, final Object array) throws IOException {

		final int arrayLength = Array.getLength(array);
		for (int i = 0; i < arrayLength; i++) {
			try {
				this.write(dos, Array.getDouble(array, i));
			} catch (ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
				// Ignore it.
			}
		}
	}
}